﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace MachineLearning {
    class XmlToLinq {
        XElement _root = null;

        XElement _sampleRowElement = null;
        public XElement SampleRowElement {
            get { return _sampleRowElement; }
        }

        IEnumerable<XElement> _rows = null;
        public IEnumerable<XElement> Rows {
            get { return _rows; }
        }

        public XmlToLinq(string xmlFilePath) {
            _root = XElement.Load(xmlFilePath);
            _rows = from el in _root.Elements("row")
                    select el;
            foreach (XElement e in _rows) {
                //just get the first element in the set
                _sampleRowElement = e;
                break;
            }
        }

        public IEnumerable<XElement> getRows(string aName, string aValue) {
            IEnumerable<XElement> rows = from el in _root.Elements("row")
                                         where (string)el.Attribute(aName) == aValue
                                         select el;
            return rows;
        }

        public IEnumerable<XElement> refineQuery(IEnumerable<XElement> rows
            , XName aName, string aValue) {
            IEnumerable<XElement> subRows = from el in rows
                                            where (string)el.Attribute(aName) == aValue
                                            select el;
            return subRows;
        }


        public List<string> getPossibleAttributeValues(XName aName) {
            List<string> possibleValues = new List<string>();
            foreach (XElement row in _rows) {
                if (!possibleValues.Contains((string)row.Attribute(aName))) {
                    possibleValues.Add((string)row.Attribute(aName));
                }
            }
            return possibleValues;
        }

        public int getNumberOfExamples(IEnumerable<XElement> rows) {
            int count = 0;
            foreach (XElement e in rows)
                count++;
            return count;
        }

        public int getNumberOfExamplesValue(IEnumerable<XElement> rows
            , XName aName, string aValue) {
            int count = 0;
            foreach (XElement e in rows) {
                if ((string)e.Attribute(aName) == aValue)
                    count++;
            }
            return count;
        }
    }
}